import { defineStore } from 'pinia';

interface User {
  id: number;
  username: string;
  email: string;
  name: string;
  permissions?: any;
}

export const useUserStore = defineStore('user', {
  state: () => {
    const token = localStorage.getItem('token') || '';
    const username = localStorage.getItem('username') || '';
    const isLogin = !!token && token.trim() !== '';
    
    console.log('🏪 用户Store初始化:', {
      hasToken: !!token,
      tokenValue: token,
      tokenLength: token.length,
      username,
      isLogin,
      timestamp: new Date().toISOString()
    });
    
    return {
      token,
      username,
      user: null as User | null,
      isLogin
    };
  },
  actions: {
    setUser(token: string, username: string) {
      console.log('👤 设置用户信息:', { username, hasToken: !!token });
      this.token = token;
      this.username = username;
      this.isLogin = !!token && token.trim() !== '';
      localStorage.setItem('token', token);
      localStorage.setItem('username', username);
      console.log('✅ 用户信息已保存');
    },
    setToken(token: string) {
      console.log('🔑 设置访问令牌:', { hasToken: !!token });
      this.token = token;
      this.isLogin = !!token && token.trim() !== '';
      localStorage.setItem('token', token);
      console.log('✅ 访问令牌已保存');
    },
    setUserInfo(user: User) {
      console.log('👤 设置用户详细信息:', user);
      this.user = user;
      this.username = user.username;
      localStorage.setItem('username', user.username);
      console.log('✅ 用户详细信息已保存');
    },
    logout() {
      console.log('🚪 用户登出');
      this.token = '';
      this.username = '';
      this.user = null;
      this.isLogin = false;
      localStorage.removeItem('token');
      localStorage.removeItem('username');
      console.log('✅ 用户信息已清除');
    }
  }
}); 